import {
  FillApi,
  GetSaveApi,
  SaveApi,
  SchoolCheckShow,
  ShowApi,
  UploadApi,
} from '@/services/School/SchoolApi';
import { ServerMessages } from '@/services/ServerMessages';
import {getYear, getYearMonth, ShowError} from '@/utils/format';
import type { ProColumns } from '@ant-design/pro-components';
import {
  ActionType,
  EditableProTable,
  nanoid,
  PageContainer,
  ProForm,
} from '@ant-design/pro-components';
import {Card, DatePicker, Form, message, Modal, Typography} from 'antd';
import moment from 'moment';
import React, {useEffect, useRef, useState} from 'react';
import { history } from 'umi';
import Submitter from '../Common/Submitter';
const locale = undefined;

const { Text } = Typography;

type DataSourceType = {
  id: React.Key;
  yr?: string;
  quarter?: string;
  major_desg_or_show_name?: string;
  parti_date?: string;
  task?: string;
};

const defaultData: DataSourceType[] = [
  {
    id: nanoid(),
    yr: undefined,
    quarter: undefined,
    major_desg_or_show_name: undefined,
    parti_date: undefined,
    task: undefined,
  },
];

const columns: ProColumns<DataSourceType>[] = [
  {
    title: '年度',
    dataIndex: 'yr',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
    renderFormItem: () => <DatePicker locale={locale} picker="year" />,
  },
  {
    title: '季度',
    dataIndex: 'quarter',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
    valueEnum: {
      第一季度: '第一季度',
      第二季度: '第二季度',
      第三季度: '第三季度',
      第四季度: '第四季度',
    },
  },
  {
    title: '国内外重大设计、展演名称',
    dataIndex: 'major_desg_or_show_name',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
  },
  {
    title: '参与时间',
    dataIndex: 'parti_date',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
    renderFormItem: () => <DatePicker locale={locale} picker="month" />,
  },
  {
    title: '承担任务',
    dataIndex: 'task',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
  },
  {
    title: '操作',
    valueType: 'option',
  },
];

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  const download = '4_1_4';
  const status_is_show = history.location.query.flag === 'display';
  const status_is_check = history.location.query.id && history.location.query.fill_id;
  const [dataSource, setDataSource] = useState<DataSourceType[]>(() => defaultData);
  const [editForm] = Form.useForm();
  const actionRef = useRef<ActionType>();

  const handleSaveBtn = () => {
    console.log('@Save', download);
    const data = {
      fill_id: download,
      data: dataSource,
    };
    console.log('@请求数据', data);
    SaveApi('/api/temp-save', data).then(
      (response) => {
        if (response.status === 0) {
          Modal.success({
            title: <span>保存成功！</span>,
            onOk() {
              window.location.reload()
            }
          })
        } else {
          ShowError(response.message);
        }
      },
      () => {
        ShowError(ServerMessages.error_message);
      },
    );
  };

  const upload = UploadApi(
    '/api/index/research/research-innovate/design-display-template',
    (info) => {
      console.log('@success', info);
      if (info.file.response.status === 0) {
        const data = info.file.response.data['data_' + download];
        for (let i = 0; i < data.length; i++) {
          data[i].id = nanoid();
          data[i].yr = moment(data[i].yr, 'YYYY');
          data[i].parti_date = moment(data[i].parti_date, 'YYYY-MM');
        }
        setDataSource(data)
        var id_arr = []
        for (let i = 0; i < data.length; i++) {
          id_arr.push(data[i].id)
        }
        setEditableRowKeys(id_arr)      } else {
        ShowError(info.file.response.message);
      }
    },
  );
  // 更新
  const [reload, setReload] = useState(false)
  useEffect(() => {
    // 插入
    if (status_is_check) {
          // 审核时加载内容
          SchoolCheckShow(history.location.query.id, history.location.query.fill_id).then(
            (response) => {
              console.log(response);
              if (response.status === 0) {
                for (let i = 0; i < response.message.length; i++) {
                  response.message[i].id = nanoid();
                  // response.message[i].yr = response.message[i].yr
                  //   ? moment(response.message[i].yr, 'YYYY')
                  //   : undefined;
                  // response.message[i].parti_date = response.message[i].parti_date
                  //   ? moment(response.message[i].parti_date, 'YYYY')
                  //   : undefined;
                }
                setDataSource(response.message)
                // resolve({ data: response.message });
              } else {
                // resolve(true);
              }
            },
          );
        } else if (status_is_show) {
          // 查看时加载内容
          ShowApi(download).then((response) => {
            console.log('@response', response);
            if (response.status === 0) {
              setDataSource(response.data)
              // resolve({ data: response.data });
            }
          });
          // resolve(true)
        } else {
          // resolve({data: dataSource})
          GetSaveApi('/api/show-temp-save', download).then((response) => {
            console.log('@response', response);
            if (response.status === 0) {
              for (let i = 0; i < response.data.length; i++) {
                response.data[i].id = nanoid();
                response.data[i].yr = response.data[i].yr
                  ? moment(response.data[i].yr, 'YYYY')
                  : undefined;
                response.data[i].parti_date = response.data[i].parti_date
                  ? moment(response.data[i].parti_date, 'YYYY')
                  : undefined;
              }
              setDataSource(response.data);
              var id_arr = []
              for (let i = 0; i < response.data.length; i++) {
                id_arr.push(response.data[i].id)
              }
              setEditableRowKeys(id_arr)
            } else {
              setDataSource(dataSource)
              // resolve({ data: dataSource });
            }
          });
        }
    console.log("@update", actionRef.current, dataSource)
  }, [reload])

  // useEffect(() => {
  //   console.log("@editable", dataSource)
  //   for (let i = 0; i < dataSource.length; i++) {
  //     actionRef.current.startEditable(dataSource[i].id);
  //   }
  // }, [dataSource])

  return (
    <PageContainer
      title="承担国内外重大设计与展演任务清单"
      content={
        <Typography.Text type="danger">
          1. 监测点内涵：2021年1月1日至今，学科承担国内外重大设计与展演任务情况。
          <br />
          2. 承担：牵头、参与。
          <br />
          3. 年度：请用"YYYY"格式填报。
          <br />
          4. 参与时间：请用"YYYY-MM"格式填报。
          <br/>5. 仅填写当前填报周期内新增的数据，如有删减，请告知学校管理员。
        </Typography.Text>
      }
    >
      <Card bordered={false}>
        <ProForm
          onFinish={async () => {
            if (dataSource.length === 0) {
              message.warn('请输入内容');
              return {};
            }
            return new Promise((resolve) => {
              editForm.validateFields().then(
                () => {
                  for (let i = 0; i < dataSource.length; i++) {
                    dataSource[i].yr = getYear(dataSource[i].yr);
                    dataSource[i].parti_date = getYearMonth(dataSource[i].parti_date);
                  }

                  const dataObj = {
                    data_4_1_4: dataSource,
                  };
                  console.log('@请求数据', dataObj);

                  FillApi(
                    '/api/index/research/research-innovate/design-display',
                    dataObj,
                    (response) => {
                      message.success(response.message);
                      history.push('/research/research-innovate');
                      resolve(true);
                    },
                    (response) => {
                      ShowError(response.message);
                      resolve(false);
                    },
                    () => {
                      ShowError(ServerMessages.error_message);
                      resolve(false);
                    },
                  );
                },
                () => {
                  resolve(false);
                },
              );
            });
          }}
          submitter={{
            render: (props, doms) => {
              return (
                <Submitter upload={upload} download={download} doms={doms} save={handleSaveBtn} />
              );
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
            submitButtonProps: {
              style: {
                marginLeft: '-8px',
              },
            },
          }}
        >
          <EditableProTable<DataSourceType>
            pagination={{
              pageSize: 10
            }}
            value={dataSource}
            onChange={setDataSource}
            actionRef={actionRef}
            // request={async () => {
            //   // 如果是审核或者查看,则异步加载内容
            //   return new Promise((resolve) => {
            //     if (status_is_check) {
            //       // 审核时加载内容
            //       SchoolCheckShow(history.location.query.id, history.location.query.fill_id).then(
            //         (response) => {
            //           console.log(response);
            //           if (response.status === 0) {
            //             resolve({ data: response.message });
            //           } else {
            //             resolve(true);
            //           }
            //         },
            //       );
            //     } else if (status_is_show) {
            //       // 查看时加载内容
            //       ShowApi(download).then((response) => {
            //         console.log('@response', response);
            //         if (response.status === 0) {
            //           resolve({ data: response.data });
            //         }
            //       });
            //       // resolve(true)
            //     } else {
            //       // resolve({data: dataSource})
            //       GetSaveApi('/api/show-temp-save', download).then((response) => {
            //         console.log('@response', response);
            //         if (response.status === 0) {
            //           for (let i = 0; i < response.data.length; i++) {
            //             response.data[i].id = nanoid();
            //             response.data[i].yr = response.data[i].yr
            //               ? moment(response.data[i].yr, 'YYYY')
            //               : undefined;
            //             response.data[i].parti_date = response.data[i].parti_date
            //               ? moment(response.data[i].parti_date, 'YYYY')
            //               : undefined;
            //           }
            //           resolve({ data: response.data });
            //           for (let i = 0; i < response.data.length; i++) {
            //             actionRef.current.startEditable(response.data[i].id);
            //           }
            //           setDataSource(response.data);
            //         } else {
            //           resolve({ data: dataSource });
            //         }
            //       });
            //     }
            //   });
            // }}
            columns={columns}
            rowKey="id"
            recordCreatorProps={{
              newRecordType: 'dataSource',
              record: () => ({
                id: nanoid(),
              }),
              style: {
                display: status_is_show || status_is_check ? 'none' : 'block',
              },
            }}
            editable={{
              type: 'multiple',
              form: editForm,
              editableKeys,
              actionRender: (row, config, defaultDoms) => {
                return [defaultDoms.delete];
              },
              onValuesChange: (record, recordList) => {
                if (record) {
                  setDataSource(recordList);
                } else {
                  // recordList 代表表单的真实数据，但是在空值检测时会变成空值，
                  // 所以只在有输入变化时同步到 DataSource，可以通过 record 来判断是否有输入。
                  // 执行删除操作时，DataSource 应该删掉 recordList 中不存在的项目。
                  let index_list = [];
                  for (let i = 0; i < recordList.length; i++) {
                    index_list.push(recordList[i].id);
                  }
                  let newDataSource = [];
                  for (let i = 0; i < dataSource.length; i++) {
                    if (index_list.indexOf(dataSource[i].id) !== -1) {
                      newDataSource.push(dataSource[i]);
                    }
                  }
                  setDataSource(newDataSource);
                }
              },
              onChange: setEditableRowKeys,
            }}
            style={{ marginBottom: 20 }}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
